package com.koron.util;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class PDFUtils {

    // pdf模板路径
    public static final String tempPath = "template/pdf/processingNotice.pdf";
    // 输出路径
    public static final String outPath = "template/pdf/out.pdf";
    // 生成二维码路径
    public static final String prCodePath = "template/pdf/prCode.png";

    // 给模板上写入数据
    public static String editPDFField(String templatePath, List<String> list,String prCodePath) {
        FileOutputStream output = null;
        PdfReader pdfReader;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PdfStamper pdfStamper;
        Document doc = new Document();
        String outPDFPath = null;
        try {
            // 生成的新文件路径
            outPDFPath = PDFUtils.class.getClassLoader().getResource("template/pdf/").getPath().replaceAll("file:/", "") + "out.pdf";
            output = new FileOutputStream(outPDFPath);
            pdfReader = new PdfReader(templatePath);
            pdfStamper = new PdfStamper(pdfReader, bos);
            AcroFields form = pdfStamper.getAcroFields();
            int index = 0;
            Iterator<String> iterator = form.getFields().keySet().iterator();
            while (iterator.hasNext() && index < list.size()) {
                String name = iterator.next().toString();
                System.out.println(name);
                form.setField(name, list.get(index++));
            }
            // 图片处理
            if(prCodePath != null){
                int pageNo = form.getFieldPositions("prCode").get(0).page;
                Rectangle signRect = form.getFieldPositions("prCode").get(0).position;
                float x = signRect.getLeft();
                float y = signRect.getBottom();
                //根据路径读取图片
                Image image = Image.getInstance(prCodePath);
                //获取图片页面
                PdfContentByte under = pdfStamper.getOverContent(pageNo);
                //图片大小自适应
                //图片大小自适应
                image.scaleToFit(signRect.getWidth(), signRect.getHeight());
                //添加图片
                image.setAbsolutePosition(x, y);
                under.addImage(image);
            }



            pdfStamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑，一定要设为true
            pdfStamper.close();

            PdfCopy copy = new PdfCopy(doc, output);
            doc.open();

            PdfImportedPage importPage = null;
            ///循环是处理成品只显示一页的问题
            for (int j = 1; j <= pdfReader.getNumberOfPages(); j++) {
                importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), j);
                copy.addPage(importPage);
            }
            doc.close();
            output.close();
            bos.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return outPDFPath;
    }

    public static void main(String[] args) {

        File file = new File("http://10.13.1.248:10041/fileService/fileDownload?path=WeChatBusiness/2020-07/15946951265212MYFLK.png");
        try {
            URL url = new URL("http://10.13.1.248:10041/fileService/fileDownload?path=WeChatBusiness/2020-07/15946951265212MYFLK.png");
            URLConnection connection = url.openConnection();
            InputStream inputStream1 = connection.getInputStream();
            FileOutputStream out = new FileOutputStream("E:/15946951265212MYFLK.png");
//            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];        //缓冲区
            int ch;
            while ((ch=inputStream1.read(buffer))!=-1){
                out.write(buffer,0,ch);
            }
            out.close();

            File file1 = new File("");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        String templatePath = PDFUtils.class.getClassLoader().getResource(tempPath).getPath();
        List<String> list = new ArrayList<>();
        list.add("123");
        list.add("456");
//        editPDFField(templatePath, list);
    }
}